package com.mdroid.support.widgets.text;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.style.ImageSpan;

/**
 * 对图片的位置进行微调
 * @author William.cheng
 * @version 创建时间：2011-11-19 上午10:56:23
 */
public class ImageSpanF extends ImageSpan {

    public ImageSpanF(Bitmap b) {
        super(b);

    }

    public ImageSpanF(Drawable d) {
        super(d);

    }

    public ImageSpanF(Bitmap b, int verticalAlignment) {
        super(b, verticalAlignment);

    }

    public ImageSpanF(Context context, Bitmap b) {
        super(context, b);

    }

    public ImageSpanF(Drawable d, int verticalAlignment) {
        super(d, verticalAlignment);

    }

    public ImageSpanF(Drawable d, String source) {
        super(d, source);

    }

    public ImageSpanF(Context context, Uri uri) {
        super(context, uri);

    }

    public ImageSpanF(Context context, int resourceId) {
        super(context, resourceId);

    }

    public ImageSpanF(Context context, Bitmap b, int verticalAlignment) {
        super(context, b, verticalAlignment);

    }

    public ImageSpanF(Drawable d, String source, int verticalAlignment) {
        super(d, source, verticalAlignment);

    }

    public ImageSpanF(Context context, Uri uri, int verticalAlignment) {
        super(context, uri, verticalAlignment);

    }

    public ImageSpanF(Context context, int resourceId, int verticalAlignment) {
        super(context, resourceId, verticalAlignment);

    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end,
            FontMetricsInt fm) {
        Drawable d = getCachedDrawable();
        Rect rect = d.getBounds();

        if (fm != null) {
            fm.ascent = -rect.bottom + 8;
            fm.descent = 8; 

            fm.top = fm.ascent;
            fm.bottom = fm.descent;
        }

        return rect.right;
    }
    
    private WeakReference<Drawable> mDrawableRef;
    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<Drawable>(d);
        }

        return d;
    }
}
